package com.tiejun.ge.http.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.tiejun.ge.common.core.constant.HttpStatus;
import com.tiejun.ge.http.config.ApiConfig;
import com.tiejun.ge.http.service.RestTemplateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: springboot
 * @description: RestTemplateService
 * @author: getiejun
 * @create: 2025-08-14 23:17
 **/
@Service
@Slf4j
public class RestTemplateServiceImpl implements RestTemplateService {

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private ApiConfig apiConfig;

    @Override
    public void getHelloWorld() {
        String url = apiConfig.getUrl() + ApiConfig.HELLO_WORLD_PATH;
        JSONObject jsonObject = restTemplate.getForObject(url, JSONObject.class);
        if(jsonObject.get("code").equals(HttpStatus.SUCCESS)) {
            log.info("url:{}, response data is:{}", url, JSONUtil.toJsonStr(jsonObject));
        } else {
            log.error(">>RestTemplateServiceImpl getHelloWorld method. The request error. the url is:{}", url);
        }
    }

    @Override
    public void getUserInfo() {
        String url = apiConfig.getUrl() + ApiConfig.USER_DETAIL;

        Map<String, Object> requestParam = new HashMap<>();
        requestParam.put("id", 1L);

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Content-Type", "application/json;charset=utf-8");
        HttpEntity httpEntity = new HttpEntity(requestParam, httpHeaders);

        JSONObject jsonObject = restTemplate.postForObject(url, httpEntity, JSONObject.class);

        if(jsonObject.get("code").equals(HttpStatus.SUCCESS)) {
            log.info("url:{}, response data is:{}", url, JSONUtil.toJsonStr(jsonObject));
        } else {
            log.error(">>RestTemplateServiceImpl getUserInfo method. The request error. the url is:{}", url);
        }
    }
}
